#include<iostream>
#include<unistd.h>
#include<pthread.h>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<ctime>
#include<semaphore.h>
#include<vector>
#include<string>
#include"Task.hpp"
#include"RingQueue.hpp"


struct Data
{
    Data(std::string name,RingQueue<Task>* rq)
    :_name(name),_rq(rq)
    {}
    
    std::string _name;
    RingQueue<Task>* _rq;
};

void* productor_start_routine(void* arg)
{
    char ops[]="+-*\%";
    Data* pdata= (Data*)arg;
    RingQueue<Task>* rq = pdata->_rq;
    std::string name=pdata->_name;

    while(1)
    {
        int x=rand()%10;
        int y=rand()%10;
        char op=ops[rand()%5];
        Task t(x,y,op,mymath);
        rq->push(t);
        std::cout<<name<<"推送了一个任务:"<<t.tostring()<<std::endl;
        usleep(100000);
    }
    delete pdata;
    return nullptr;
}


void* consumer_start_routine(void* arg)
{
    Data* pdata= (Data*)arg;
    RingQueue<Task>* rq = pdata->_rq;
    std::string name=pdata->_name;

    while(1)
    {
        Task t;
        rq->pop(&t);
        std::cout<<name<<"收到了一个任务,结果是："<<t()<<std::endl;
        usleep(100000);
    }
    delete pdata;
    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr));
    RingQueue<Task>* rq=new RingQueue<Task>();

    // pthread_t ctid,ptid;
    // char* name1 = new char[64];
    // snprintf(name1 ,64,"Productor Thread 1");
    // Data* data1 = new Data(name1,rq);
    // delete[] name1;
    // pthread_create(&ptid,nullptr,productor_start_routine,data1);

    // char* name2 = new char[64];
    // snprintf(name2 ,64,"Consumer Thread 1");
    // Data* data2 = new Data(name2,rq);
    // delete[] name2;
    // pthread_create(&ctid,nullptr,consumer_start_routine,data2);


    pthread_t ctids[5]; //消费者
    pthread_t ptids[5]; //生产者    

    //创建生产者线程
    for(int i=0;i<5;++i)
    {
        char* name = new char[64];
        snprintf(name ,64,"Productor Thread %d",i+1);
        Data* data = new Data(name,rq);
        delete[] name;
        pthread_create(ptids+i,nullptr,productor_start_routine,data);
    }
    //创建消费者线程
    for(int i=0;i<5;++i)
    {
        char* name = new char[64];
        snprintf(name ,64,"Consumer Thread %d",i+1);
        Data* data = new Data(name,rq);
        delete[] name;
        pthread_create(ctids+i,nullptr,consumer_start_routine,data);
    }

    while(1) sleep(1);

    //既然走不到这里，也懒得join了

    return 0;
}